package com.company;

import java.io.File;
import java.io.FileOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDP_File_Receiver {

    public static void main(String[] args) throws Exception{
        DatagramSocket ds = new DatagramSocket(4603);
        DatagramSocket ds2 = new DatagramSocket(8000);

        while(true){
            byte[] buf = new byte[1024];
            DatagramPacket dp = new DatagramPacket(buf,buf.length);
            ds.receive(dp);
            String fileName = new String(dp.getData(),0,dp.getLength());

            new Thread(new ThreadFileTransfer(fileName,ds2)).start();
        }


    }
}

class ThreadFileTransfer implements Runnable{

    private DatagramSocket ds;
    private DatagramPacket dp;
    private String fileName;
    private byte[] buf = new byte[1024];

    public ThreadFileTransfer(String fileName,DatagramSocket ds){
        this.ds = ds;
        this.fileName = fileName;
        dp = new DatagramPacket(buf,buf.length);
    }

    @Override
    public void run() {
        try {
            File filePath = new File("D:\\FileTransfer\\");
            if(!filePath.exists()) {
                filePath.mkdir();
            }

            File file = new File(filePath,fileName);
            System.out.println("接收文件" + fileName + "中……");

            FileOutputStream fos = new FileOutputStream(file);
            int len;
            do{
                ds.receive(dp);;
                len = dp.getLength();
                fos.write(buf,0,len);
                fos.flush();
                Thread.sleep(10);
            }while(len > 0);
            fos.close();
            System.out.println("接收文件" + fileName + "完毕！");



        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
